'''
Created on Jul 12, 2012

@author: byron
'''

import sqlite3
import wx
import wx.lib.sized_controls as sc
import datetime

class Stats(object):

    def __init__(self):
        self.conn = sqlite3.connect('stats.db')
        c = self.conn.cursor()
        c.execute('create table if not exists stats (date timestamp, temperature real, humidity real)')
        self.conn.commit()
        c.close()
        
    def LogData(self, temp, hum):
        c = self.conn.cursor()
        c.execute('insert into stats values (?, ?, ?)', (datetime.datetime.now(), temp, hum))
        self.conn.commit()
        c.close()
        
    def GetLogs(self):
        c = self.conn.cursor()
        results = []
        for row in c.execute('select datetime(date), temperature, humidity from stats order by date desc limit 500'):
            results.append(row)
        
        c.close()   
        
        return results
    
    def TemperatureStats(self):
        c = self.conn.cursor()
        c.execute('select min(temperature), max(temperature), round(avg(temperature), 2) from stats')
        result =  c.fetchone()
        c.close()
        return result
    
    def HumidityStats(self):
        c = self.conn.cursor()
        c.execute('select min(humidity), max(humidity), round(avg(humidity), 2) from stats')
        result =  c.fetchone()
        c.close()
        return result
    
    def ClearLogs(self):
        c = self.conn.cursor()
        c.execute('delete from stats')
        self.conn.commit()
        c.close()
        
class StatsDialog(sc.SizedDialog):
    def __init__(self, *args, **kwargs):
        
        self.stats = kwargs['stats']
        del kwargs['stats'] 
        
        sc.SizedDialog.__init__(self, None, -1, "Stats", style=wx.DEFAULT_DIALOG_STYLE)
        list_id = wx.NewId()
        
        pane = self.GetContentsPane()
        
        tmp_stats = self.stats.TemperatureStats()
        hum_stats = self.stats.HumidityStats()
        
        wx.StaticText(pane, -1, "Temperature (Min: {0}, Max: {1}, Avg: {2})".format(tmp_stats[0], tmp_stats[1], tmp_stats[2]))
        wx.StaticText(pane, -1, "Humidity (Min: {0}%, Max: {1}%, Avg: {2}%)".format(hum_stats[0], hum_stats[1], hum_stats[2]))

        self.list = wx.ListCtrl(pane, list_id, style=wx.LC_REPORT|wx.SUNKEN_BORDER, size=(300,200))
        self.list.Show(True)
        
        self.list.InsertColumn(0, "Date")
        self.list.InsertColumn(1, "Temperature")
        self.list.InsertColumn(2, "Humidity")
        
        self.list.SetColumnWidth(0, 120)
        self.list.SetColumnWidth(1, 80)
        self.list.SetColumnWidth(2, 70)
                
        self.data = self.stats.GetLogs()
        self.data.reverse()
        
        for row in self.data:
            index = self.list.InsertStringItem(0, str(row[0]))
            self.list.SetStringItem(index, 1, str(row[1]))
            self.list.SetStringItem(index, 2, str(row[2]))
            
        btnpane = sc.SizedPanel(pane, -1)
        btnpane.SetSizerType("horizontal")
        btnpane.SetSizerProps(expand=True)

        self.clearBtn = wx.Button(btnpane, -1, "Clear")
        spacer = sc.SizedPanel(btnpane, -1)
        spacer.SetSizerProps(expand=True, proportion=1)
        self.saveBtn = wx.Button(btnpane, wx.ID_OK)
        
        self.Bind(wx.EVT_BUTTON, self.onClear, self.clearBtn)

        self.Fit()
        self.SetMinSize(self.GetSize())
        
    def onClear(self, event):
        dlg = wx.MessageDialog(self,
            "Do you really want to delete all the statistics?",
            "Confirm Exit", wx.YES|wx.NO|wx.ICON_QUESTION)
        result = dlg.ShowModal()
        dlg.Destroy()
        if result == wx.ID_YES:
            self.stats.ClearLogs()
            self.list.ClearAll()
    